package algorithm.avl;


import algorithm.trie.FileOperation;
import sun.invoke.util.BytecodeName;

import java.util.ArrayList;
import java.util.List;

/**
 * @author bingo
 * @Description
 * @Date 2018/7/13
 */
public class AVLTree<Key extends Comparable<Key>,Value> {

    public class  Node{

        private Key key;

        private  Value value;

        private Node left;

        private Node right;

        private int height;

        public Node(Key key, Value value) {
            this.key=key;
            this.value=value;
            this.left=right = null;
            this.height = 0;
        }

    }

    private int count;

    private Node root;

    public AVLTree() {
        this.count = 0;
        this.root = null;
    }

    public int  getSize(){

        return count;
    }

    public boolean isEmpty(){

        return  count==0;
    }

    private int getHeight(Node node){
        if (node==null){
            return 0;
        }
        return node.height;
    }

    private int  balanceFactor(Node node){

        if(node==null){
            return 0;
        }

        return  getHeight(node.left)-getHeight(node.right);
    }

    /**添加元素**/
    public void insert(Key key,Value value){
        root = insert(root ,key,value);
    }

    private Node insert(Node node, Key key, Value value) {
        if(node == null){
            count++;
            return  new  Node(key,value);
        }
        if(key.compareTo(node.key) == 0){
            node.value=value;
        }
        else if(key.compareTo(node.key)<0){
            node.left =insert(node.left,key,value);
        }
        else{
            node.right = insert(node.right,key,value);
        }
            //计算高度
            node.height = 1+Math.max(getHeight(node.left),getHeight(node.right));
         //计算平衡因子
          int balanceFactor = balanceFactor(node);
          // LL
          if(balanceFactor > 1 && balanceFactor(node.left) >= 0){
              return rightRotate(node);
              }
              //RR
          if(balanceFactor < -1 && balanceFactor(node.right) <= 0){         //进行右旋
            return leftRotate(node);
        }

        //LR
        if(balanceFactor > 1 && balanceFactor(node.left) < 0){
              node.left = leftRotate(node.left);
              return  rightRotate(node);
        }
        //RL
        if(balanceFactor < -1 && balanceFactor(node.right) > 0) {
            node.right = rightRotate(node.right);
            return leftRotate(node);
        }

        return node;
    }
    /**
       对节点y进行向右旋转操作，返回旋转后新的根节点x
            y                              x
           / \                           /   \
          x   T4     向右旋转 (y)        z     y
         / \       - - - - - - - ->    / \   / \
        z   T3                       T1  T2 T3 T4
       / \
     T1   T2
     */
    public Node rightRotate(Node y){
        //旋转
        Node x = y.left;
        Node t3 = x.right;
        x.right = y;
        y.left = t3;
        //维维护高度

        y.height =  Math.max(getHeight(y.left),getHeight(y.right))+1;
        x.height =  Math.max(getHeight(x.left),getHeight(x.right))+1;

        return x;
    }
    /** 对节点y进行向左旋转操作，返回旋转后新的根节点x
        y                             x
      /  \                          /   \
     T1   x      向左旋转 (y)       y     z
         / \   - - - - - - - ->   / \   / \
       T2  z                     T1 T2 T3 T4
          / \
         T3 T4
     */
    public Node leftRotate(Node y){
        //旋转
    Node x = y.right;
    Node t2 = x.left;
    x.left = y;
    y.right = t2;
    //维护高度
    y.height =  Math.max(getHeight(y.left),getHeight(y.right))+1;
    x.height =  Math.max(getHeight(x.left),getHeight(x.right))+1;
    return x;

    }

 /**
  *  前序遍历
  * */
    public void preOrder(){
    List<Key>  list = new ArrayList<>();
        preOrder(root,list);

    }
/**
 *   前序遍历递归函数
 *   @param node  节点
 *   @param list  集合
 *
 * */
     private void preOrder(Node node, List<Key> list) {

        if (node==null){
            return;
        }
        preOrder(node.left,list);
        list.add(node.key);
        preOrder(node.right,list);

    }
   /**
    *  判断是否是一颗二分搜索树
    * */
    public boolean isBST(){

        List<Key> list = new ArrayList<>();
        preOrder(root,list);
        for(int i=1;i<list.size();i++){
            if(list.get(i).compareTo(list.get(i-1))<0){
                return  false;
            }
        }
        return  true;
    }

   /**
    * 判断是否是一颗平衡二叉树
    *
    * */
    public boolean isBalanced(){

       return isBalanced(root);

    }
    /**
     *  判断是否是平衡二叉树递归
     *
     */

    private boolean isBalanced(Node node) {
        if(node==null){
            return  true;
        }
       int balanceFactor =  balanceFactor(node);
        if(Math.abs(balanceFactor)>1){
            return  false;
        }

        return  isBalanced(node.left) && isBalanced(node.right);
    }

    public Node getNode(Key key){

        return getNode(root,key);
    }

    public Value get(Key key){

        Node node = getNode(root,key);

        return  node==null ? null : node.value;
    }

    private Node getNode(Node node, Key key) {

        if(node==null){
            return  null;
        }

        if(node.key.compareTo(key)==0){

            return  node;
        } else if(key.compareTo(node.key)>0){

            return  getNode(node.right,key);

        }
        else {
            return  getNode(node.left,key);
        }
    }

    public void set(Key key,Value value){

        Node  res = getNode(key);
        if(res==null){
            throw  new IllegalArgumentException("doesn't have key called"+key);
        }
        res.value = value;
    }

    public void removeMin(){
        if(root!=null){
            root= removeMin(root);
        }
    }

    private Node removeMin(Node node){
        if(node.left==null){
            Node rightNode = node.right;
            node.right=null;
            count--;
            return rightNode;
        }
        node.left =  removeMin(node.left);
        return node;
    }
    public Node getMin(Node node) {
        if (node.left == null) {
            return node;
        }

        return getMin(node.left);
    }
    public boolean contains(Key key){
        return getNode(root, key) != null;
    }

    public  Node removeNode(Key key){

        return  removeNode(root,key);
    }
   /**
    *    移除任意节点
    *
    * */
    private Node removeNode(Node node,Key key){

        if(node==null){
            return null;
        }
        if(node.key.compareTo(key)>0){
            return  node.left =  removeNode(node.left,key);
        }
        Node retNode ;
        if(node.key.compareTo(key)<0){
            return node.right =  removeNode(node.right,key);
        }
        else{
            if(node.right==null){
                Node  leftNode = node.left;
                node.left=null;
                retNode = leftNode;
            }
            else if(node.left==null){
                Node rightNode = node.right;
                node.right=null;
                retNode = rightNode;

            }
            else {
                Node processorNode = getMin(node.right);
                processorNode.right = removeMin(node.right);
                processorNode.left = node.left;
                node.left = node.right = null;
                retNode = processorNode;
            }
        }
        if(retNode == null)
            return null;

        // 更新height
        retNode.height = 1 + Math.max(getHeight(retNode.left), getHeight(retNode.right));

        // 计算平衡因子
        int balanceFactor =  balanceFactor(retNode);

        // 平衡维护
        // LL
        if (balanceFactor > 1 &&  balanceFactor(retNode.left) >= 0)
            return rightRotate(retNode);

        // RR
        if (balanceFactor < -1 &&  balanceFactor(retNode.right) <= 0)
            return leftRotate(retNode);

        // LR
        if (balanceFactor > 1 &&  balanceFactor(retNode.left) < 0) {
            retNode.left = leftRotate(retNode.left);
            return rightRotate(retNode);
        }

        // RL
        if (balanceFactor < -1 &&  balanceFactor(retNode.right) > 0) {
            retNode.right = rightRotate(retNode.right);
            return leftRotate(retNode);
        }

        return retNode;

    }

    public static void main(String[] args) {
        AVLTree avlTree = new AVLTree();
        String fileName= "demo/pride-and-prejudice.txt";
        List<String> words = new ArrayList<>();
        FileOperation.readFile(fileName,words);
        for(String word:words){
            if(avlTree.contains(word)){
                avlTree.set(word,(int)avlTree.get(word)+1);
            }
            else{
                avlTree.insert(word,1);
            }

        }
        System.out.println("Total different words: " + avlTree.getSize());
        System.out.println("Frequency of PRIDE: " + avlTree.get("pride"));
        System.out.println("Frequency of PREJUDICE: " + avlTree.get("prejudice"));
        System.out.println("is BST："+avlTree.isBST());
        System.out.println("is balanced："+avlTree.isBalanced());


    }


}
